'use strict';

const db = uniCloud.database()
const ordersCollection = db.collection('orders')

exports.main = async (event, context) => {
	const { 
		courseId,
		courseName,
		courseImage,
		price,
		personCount,
		totalPrice,
		tripDate,
		meetingPoint,
		meetingTime,
		
	} = event
	
	// 参数校验
	if (!courseId || !courseName || !price || !tripDate || !meetingPoint || !meetingTime) {
		return {
			code: 1,
			message: '参数不完整'
		}
	}
	
	// 获取用户信息
	const { USERID } = event
	const userId = USERID 
	
	if (!userId) {
		return {
			code: 2,
			message: '未登录'
		}
	}
	
	try {
		// 创建订单记录
		const orderData = {
			courseId,
			courseName,
			courseImage,
			userId: userId,
			userName: event.userName || '用户' + userId.substr(-4),
			userAvatar: event.userAvatar || '/static/images/default-avatar.png',
			price,
			personCount: personCount || 1,
			totalPrice: totalPrice || price,
			tripDate,
			meetingPoint,
			meetingTime,
			status: 'upcoming',
			createTime: Date.now(),
			updateTime: Date.now()
		}
		
		const result = await ordersCollection.add(orderData)
		
		return {
			code: 0,
			message: '创建成功',
			data: {
				orderId: result.id
			}
		}
	} catch (e) {
		console.error(e)
		return {
			code: 3,
			message: '创建失败'
		}
	}
} 